/*!
    \file    main.c
    \brief   data encrypt/decrypt by using CAU and RTDEC example

    \version 2025-01-24, V1.4.0, firmware for GD32H7xx
*/

/*
    Copyright (c) 2025, GigaDevice Semiconductor Inc.

    Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice, this
       list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright notice,
       this list of conditions and the following disclaimer in the documentation
       and/or other materials provided with the distribution.
    3. Neither the name of the copyright holder nor the names of its contributors
       may be used to endorse or promote products derived from this software without
       specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
*/

#include "gd32h7xx.h"
#include "ospi_operation.h"
#include "gd32h759i_eval.h"
#include "systick.h"
#include <stdio.h>

#define OSPI_PERIPH             OSPI0

#define RTDEC_CLK               RCU_RTDEC0
#define RTDEC_USE               RTDEC0
#define AREA_USE                RTDEC_AREA1
#define AREA_START_ADDR         (uint32_t)0x90020000U
#define AREA_END_ADDR           (uint32_t)0x900201FFU
#define AREA_READ_WRITE_ADDR    (uint32_t)0x00000000U

#define OSPI_START_ADDR         (uint32_t)0x90000000U

#define TEXT_SIZE               (uint16_t)0x0100U

uint32_t rtdec_key[4]          = {0x01234567, 0x89ABCDEF, 0x01234567, 0x89ABCDEF};
uint32_t nonce[2]              = {0x89ABCDEF, 0x01234567};
uint16_t fw_version            = 0x0112U;

uint32_t aes_key[4];
uint32_t vectors[4];
uint32_t swapped_vectors[4];
uint8_t plain_text[TEXT_SIZE]  = "This message is encrypted by CAU and decrypted by RTDEC based on GD32H7 MCU.\r\n";
uint8_t swapped_plain_text[TEXT_SIZE];
uint8_t ciper_text[TEXT_SIZE];
uint8_t swapped_ciper_text[TEXT_SIZE];

uint8_t read_test[TEXT_SIZE];

__IO uint32_t *ospi_memory_addr;

void cache_enable(void);
static void rtdec_struct_init(rtdec_parameter_struct *rtdec_struct);
static uint8_t crc_cal(uint32_t *keyin);
static void plain_text_encrypt(void);

/*!
    \brief      main function
    \param[in]  none
    \param[out] none
    \retval     none
*/
int main(void)
{
    ospi_parameter_struct ospi_struct;
    rtdec_parameter_struct rtdec_struct;
    uint32_t flash_id;
    uint32_t *preaddata = NULL;
    uint16_t i;

    /* enable I-Cache and D-Cache */
    cache_enable();

    systick_config();

    /* configure USART */
    gd_eval_com_init(EVAL_COM);

    printf("RTDEC decrupt data from OSPI flash example.\r\n");

    /* configure OSPI_PERIPH */
    ospi_config(OSPI_PERIPH, &ospi_struct);
    ospi_enable(OSPI_PERIPH);

    /* read flash id */
    flash_id = ospi_flash_read_id(OSPI_PERIPH, &ospi_struct);
    printf("OSPI flash id is : 0x%04X.", flash_id);

    /* encrypt the plain text */
    plain_text_encrypt();

    /*OSPI flash reset memory */
    ospi_flash_reset_enable(OSPI_PERIPH, &ospi_struct);
    ospi_flash_reset_memory(OSPI_PERIPH, &ospi_struct);
    delay_1ms(5);

    /* erase flash sector for specified address */
    ospi_flash_autopolling_memory_ready(OSPI_PERIPH, &ospi_struct, SPI_MODE);
    ospi_flash_write_enable(OSPI_PERIPH, &ospi_struct);
    ospi_flash_sector_erase(OSPI_PERIPH, &ospi_struct, AREA_START_ADDR - OSPI_START_ADDR);
    ospi_flash_autopolling_memory_ready(OSPI_PERIPH, &ospi_struct, SPI_MODE);

    /* OSPI flash page progrom */
    ospi_flash_autopolling_memory_ready(OSPI_PERIPH, &ospi_struct, SPI_MODE);
    ospi_flash_write_enable(OSPI_PERIPH, &ospi_struct);
    ospi_flash_page_program(OSPI_PERIPH, &ospi_struct, AREA_START_ADDR - OSPI_START_ADDR, TEXT_SIZE, (uint8_t *)ciper_text);
    ospi_flash_autopolling_memory_ready(OSPI_PERIPH, &ospi_struct, SPI_MODE);

    /* configure RTDEC */
    rcu_periph_clock_enable(RTDEC_CLK);
    rtdec_struct_para_init(&rtdec_struct);
    /* initialize rtdec_struct parameter */
    rtdec_struct_init(&rtdec_struct);
    /* initialize rtdec peripheral */
    rtdec_init(RTDEC_USE, AREA_USE, &rtdec_struct);
    /* lock rtdec key */
    rtdec_lock(RTDEC_USE, AREA_USE, RTDEC_ARE_K_LK);
    /* enable RTDEC0 */
    rtdec_enable(RTDEC_USE, AREA_USE);
    /* lock rtdec register */
    rtdec_lock(RTDEC_USE, AREA_USE, RTDEC_ARE_CFG_LK);

    /* configure OSPI FLASH dummy cycles */
    ospi_flash_write_enable(OSPI_PERIPH, &ospi_struct);
    ospi_flash_write_volatile_cfg_reg(OSPI_PERIPH, &ospi_struct, GD25LX512ME_CFG_REG1_ADDR, GD25LX512ME_CFG_16_DUMMY_CYCLES);

    /* configure OSPI FLASH enter STR OSPI mode */
    ospi_flash_write_enable(OSPI_PERIPH, &ospi_struct);
    ospi_flash_write_volatile_cfg_reg(OSPI_PERIPH, &ospi_struct, GD25LX512ME_CFG_REG0_ADDR, GD25LX512ME_CFG_OCTAL_STR_WO);
    ospi_flash_autopolling_memory_ready(OSPI_PERIPH, &ospi_struct, OSPI_MODE);

    /* enable memory map mode */
    ospi_memory_map_enable(OSPI_PERIPH, &ospi_struct);

    ospi_memory_addr = (uint32_t *)AREA_START_ADDR + AREA_READ_WRITE_ADDR;

    /* read data in memory map mode with RTDEC decrypt */
    preaddata = (uint32_t *)read_test;
    for(i = 0; i < TEXT_SIZE / 4; i++) {
        preaddata[i] = *(uint32_t *)(ospi_memory_addr + i);
    }

    /* compare read decrypted data to the plain data */
    for(i = 0; i < TEXT_SIZE; i++) {
        if(read_test[i] != plain_text[i]) {
            printf("RTDEC decrypt data is failed, data index is: %d.\r\n", i);

            while(1) {
            }
        }
        ospi_memory_addr++;
    }

    printf("The decpyted result by RTDEC is: %s\r\n", read_test);

    printf("RTDEC decrypt data is successed.\r\n");

    while(1) {
    }
}

/*!
    \brief      enable the CPU Chache
    \param[in]  none
    \param[out] none
    \retval     none
*/
void cache_enable(void)
{
    /* enable I-Cache */
    SCB_EnableICache();

    /* enable D-Cache */
    SCB_EnableDCache();
}

/*!
    \brief      initialize rtdec struct
    \param[in]  rtdec_struct: RTDEC parameter initialization stuct members of the structure
    \param[out] none
    \retval     none
*/
static void rtdec_struct_init(rtdec_parameter_struct *rtdec_struct)
{
    rtdec_struct->access_mode = RTDEC_MODE_DATA_ACCESS;
    rtdec_struct->key = rtdec_key;
    rtdec_struct->nonce = nonce;
    rtdec_struct->key_crc = crc_cal(rtdec_struct->key);
    rtdec_struct->fw_version = fw_version;
    rtdec_struct->start_addr = AREA_START_ADDR;
    rtdec_struct->end_addr = AREA_END_ADDR;
}

/*!
    \brief      calculate key CRC by software
    \param[in]  keyin: decryption key written in the RTDEC register
    \param[out] none
    \retval     crc_val: CRC value
*/
static uint8_t crc_cal(uint32_t *keyin)
{
    const uint8_t crc7_poly = 0x07U;
    const uint32_t key_strobe[4] = {0xAA55AA55, 0x00000003, 0x00000018, 0x000000C0};
    uint8_t i, j, k, crc_val = 0x00U;
    uint32_t keyval;

    for(j = 0U; j < 4U; j++) {
        keyval = *(keyin + j);

        if(j == 0U) {
            keyval ^= key_strobe[0];
        } else {
            keyval ^= (key_strobe[j] << 24U) | (crc_val << 16U) | (key_strobe[j] << 8U) | crc_val;
        }

        for(i = 0, crc_val = 0; i < 32; i++) {
            k = (((crc_val >> 7U) ^ ((keyval >> (31U - i)) & 0x0FU))) & 1U;
            crc_val <<= 1U;
            if(k) {
                crc_val ^= crc7_poly;
            }
        }
        crc_val ^= 0x55U;
    }
    return crc_val;
}

/*!
    \brief      swap data that encrpted for CAU or decrypted fo RTDEC
    \param[in]  input: input data to be swaped
    \param[in]  size: data size
    \param[out] output: output swapped data
    \retval     none
*/
static void data_swap(uint32_t *input, uint32_t *output, uint32_t size)
{
    uint32_t i, j;
    for(i = 0; i < size; i += 4) {
        for(j = 0; j < 4; j++) {
            output[i + j] = __REV(input[i + 4 - j - 1]);
        }
    }
}

/*!
    \brief      encrypt the plain text with AES-128 in CTR mode
    \param[in]  none
    \param[out] none
    \retval     none
*/
static void plain_text_encrypt(void)
{
    cau_parameter_struct text;

    rcu_periph_clock_enable(RCU_CAU);

    /* deinitialize CAU */
    cau_deinit();
    cau_struct_para_init(&text);

    /* initialize AES initialization vector */
    vectors[0] = (AREA_USE << 28) | ((AREA_START_ADDR + AREA_READ_WRITE_ADDR) >> 4);
    vectors[1] = fw_version;
    vectors[2] = nonce[0];
    vectors[3] = nonce[1];

    data_swap((uint32_t *)plain_text, (uint32_t *)swapped_plain_text, TEXT_SIZE / 4);
    data_swap(rtdec_key, aes_key, 4);
    data_swap(vectors, swapped_vectors, 4);

    /* initialize cau parameter */
    text.alg_dir   = CAU_ENCRYPT;
    text.key       = (uint8_t *)aes_key;
    text.key_size  = 128;
    text.iv        = (uint8_t *)swapped_vectors;
    text.input     = (uint8_t *)swapped_plain_text;
    text.in_length = TEXT_SIZE;

    if(SUCCESS == cau_aes_ctr(&text, (uint8_t *)swapped_ciper_text)) {
        printf("\r\nEncrypted Data with AES 128 Mode CTR successed.\r\n");
    } else {
        printf("\r\nEncrypted Data with AES 128 Mode CTR failed.\r\n");
    }

    data_swap((uint32_t *)swapped_ciper_text, (uint32_t *)ciper_text, TEXT_SIZE / 4);
}

/* retarget the C library printf function to the USART */
int fputc(int ch, FILE *f)
{
    usart_data_transmit(EVAL_COM, (uint8_t) ch);

    while(RESET == usart_flag_get(EVAL_COM, USART_FLAG_TBE));

    return ch;
}
